package com.dpp.service.impl;

import com.dpp.context.BaseContext;
import com.dpp.dto.EditAddressDTO;
import com.dpp.dto.SaveAddressDTO;
import com.dpp.dto.TransactionsDTO;
import com.dpp.entity.*;
import com.dpp.mapper.*;
import com.dpp.result.Result;
import com.dpp.service.AddressService;
import com.dpp.vo.AddressInfoVO;
import com.dpp.vo.AddressVO;
import com.dpp.vo.OutOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserMoneyMapper userMoneyMapper;

    @Autowired
    private CouponBookMapper couponBookMapper;

    @Autowired
    private TransactionsMapper transactionsMapper;
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 修改默认地址
     *
     * @param id
     */
    @Override
    @Transactional
    public Result updateDA(Integer id) {
        String openid = BaseContext.getCurrentId();
        //查询用户所有地址
        List<AddressBook> addressBooks=addressMapper.selectAllAddress(openid);
        for (AddressBook addressBook : addressBooks) {
            if (addressBook.getId().equals(id)) {
                //先清空该用户的默认地址
                addressMapper.clearDA(openid);
                //修改该用户的默认地址为当前id的地址
                addressBook.setIsDefault(AddressBook.IS_DEFAULT);
                addressMapper.updateDA(addressBook);
                return Result.success("修改成功");
            }
        }
        return Result.error("修改失败");

    }

    /**
     * 增加用户地址信息
     *
     * @param saveAddressDTO
     */
    @Override
    @Transactional
    public Result saveAddress(SaveAddressDTO saveAddressDTO) {
        Users users = userMapper.selectByOpenId(saveAddressDTO.getOpenid());
        if (users==null)
        {
            return Result.error("无该用户");
        }
        //检查添加的地址是否合法
        String address = saveAddressDTO.getAddress();
        String phone = saveAddressDTO.getPhone();
        //根据openId查询users表得到addressId
        String openId = saveAddressDTO.getOpenid();
        //查询地址表中的地址
        AddressBook addressBook = addressMapper.selectByAddressAndUserIdAndPhone(address,openId, phone);
        //查询所有地址
        List<AddressBook> addressBooks = addressMapper.selectAllAddress(openId);
        if (addressBooks.isEmpty()) {
            //第一个地址，直接插入
            addressBook = AddressBook.builder()
                    .address(address)
                    .phone(phone)
                    .isDefault(AddressBook.IS_DEFAULT)
                    .openid(openId)
                    .build();
            //插入地址
            addressMapper.save(addressBook);
            return Result.success("新增成功");
        }

        if (addressBook != null) {
            return Result.error("地址已存在");
        }

        //将原默认地址修改
        addressMapper.clearDA(openId);

        //构造地址簿对象（设置为默认地址）
        addressBook = AddressBook.builder()
                .address(address)
                .phone(phone)
                .isDefault(AddressBook.IS_DEFAULT)
                .openid(openId)
                .build();

        //插入地址
        addressMapper.save(addressBook);
        return Result.success("新增成功");
    }

    /**
     * 编辑地址
     *
     * @param editAddressDTO
     * @return
     */
    @Transactional
    @Override
    public Result editAddress(EditAddressDTO editAddressDTO) {
        //得到这个用户
        String openid = BaseContext.getCurrentId();
        List<AddressBook> addressBooks=addressMapper.selectAllAddress(openid);




        for (AddressBook addressBook1 : addressBooks) {
            //是这个人的地址
            if (addressBook1.getId().intValue() == editAddressDTO.getId()) {

                //判断要修改的地址是否已经存在
                String address = editAddressDTO.getAddress();
                String phone = editAddressDTO.getPhone();

                AddressBook addressBook = addressMapper.selectByIdAndAddressAndUserIdAndPhone(address,openid,phone);
                //修改后的地址存在！
                if(addressBook != null){
                   AddressBook  a=addressMapper.selectById(editAddressDTO.getId());

                    if (addressBook.getAddress().equals(a.getAddress())&&addressBook.getPhone().equals(a.getPhone()))
                    {
                        System.out.println("修改后的地址为该地址本身");
                        return Result.success("保存成功");
                    }


                    //将所有地址改为非默认地址
                    addressMapper.clearDA(openid);
                    //将本次地址删除
                    addressMapper.deleteAddress(editAddressDTO.getId());
                    //将原先地址设为默认地址
                    addressMapper.updateAddress(addressBook.getId(),addressBook.getPhone(),addressBook.getAddress(),1);
                    return Result.success("保存成功");
                }

                //将所有地址改为非默认地址
                addressMapper.clearDA(openid);

                AddressBook addressBook2 = AddressBook.builder()
                        .address(address)
                        .phone(phone)
                        .isDefault(AddressBook.IS_DEFAULT)
                        .openid(openid)
                        .build();
                //修改地址簿（设为默认地址）
                Integer id = editAddressDTO.getId();
                addressMapper.updateAddress(id,editAddressDTO.getPhone(),editAddressDTO.getAddress(),AddressBook.IS_DEFAULT);
                return Result.success("保存成功");


            }
        }
        return Result.error("无权修改此地址");
    }

    @Override
    @Transactional
    public Result deleteAddress(Integer id) {
        //得到该用户所有地址
        String openid = BaseContext.getCurrentId();
        List<AddressBook> addressBooks=addressMapper.selectAllAddress(openid);
        for (AddressBook addressBook : addressBooks) {

            if (addressBook.getId().intValue()==id)
            {
                //是默认地址
                if (addressBook.getIsDefault().equals(AddressBook.IS_DEFAULT)) {
                    return Result.error("该地址为默认地址，不允许删除");
                }
                addressMapper.deleteAddress(id);
                return Result.success("删除成功");
            }
        }
        return  Result.error("");
    }

    @Override
    public AddressInfoVO getInfo(String openid) {
        //根据addressId查询地址集合
        List<AddressBook> addressBooks = addressMapper.selectAllAddress(openid);
        //格式转换（将phone转换为tel）
        List<AddressVO> addressVOS = new ArrayList<>();
        //循环遍历地址集合
        for (AddressBook addressBook : addressBooks) {
            AddressVO addressVO = new AddressVO();
            addressVO.setAddress(addressBook.getAddress());
            addressVO.setId(addressBook.getId());
            addressVO.setTel(addressBook.getPhone());
            addressVO.setIsDefault(addressBook.getIsDefault());
            addressVOS.add(addressVO);
        }
        AddressInfoVO addressInfoVO = new AddressInfoVO();
        //查询用户金额
        UserMoney userMoney = userMoneyMapper.selectById(openid);
        //添加地址集合
        addressInfoVO.setAddressList(addressVOS);
        //用户金额在表中存在
        if(userMoney!=null){
            //查询交易明细集合按时间倒序
            List<Transactions>  transactions =  transactionsMapper.selectByTakeOpenId(openid);
            if(transactions.size()>50){
                transactions=transactions.subList(0,50);
            }
            //创建交易明细集合
            List<TransactionsDTO>  transactionsDTOList = new ArrayList<>();
            for (Transactions transaction : transactions) {
                Integer moneyBefore = transaction.getMoneyBefore();
                Integer moneyAfter = transaction.getMoneyAfter();
                Integer changeMoney=moneyAfter-moneyBefore;
                TransactionsDTO transactionsDTO = new TransactionsDTO();
                BeanUtils.copyProperties(transaction,transactionsDTO);
                transactionsDTO.setChangeMoney(changeMoney);
                //添加进入交易明细
                transactionsDTOList.add(transactionsDTO);
            }
            //明细集合
            addressInfoVO.setTransactionsDTOList(transactionsDTOList);
            //设置用户金额
            addressInfoVO.setMoney(userMoney.getMoney());
            //设置用户跑跑币
            addressInfoVO.setPaopaoCoins(userMoney.getPaopaoCoins());
            return addressInfoVO;
        }
        //金额表中没有，说明该没有钱，没有交易明细
        addressInfoVO.setTransactionsDTOList(null);
        //设置交易为0
        addressInfoVO.setMoney(0);
        addressInfoVO.setPaopaoCoins(0);
        return addressInfoVO;
    }

    @Override
    @Transactional
    public OutOrderVO getDA() {
        //获取openid
        String openid = BaseContext.getCurrentId();
        if (userMapper.selectByOpenId(openid)==null) {
            return null;
        }
        OutOrderVO outOrderVO = new OutOrderVO();

        //查询默认地址
        OutOrderVO outOrderVO_ = userMapper.selectTimesAndDA(openid);
        if (outOrderVO_ != null) {
            outOrderVO.setPhone(outOrderVO_.getPhone());
            outOrderVO.setAddress(outOrderVO_.getAddress());
        }
        List<Orders> ordersList = orderMapper.selectByOpenIdAll(openid);
        outOrderVO.setIsNew(ordersList.isEmpty());
        long time = System.currentTimeMillis();
        //查询有效优惠券
        List<Coupon> coupons = couponBookMapper.selectCoupon(openid, time);
        List<Coupon> disableCoupons = couponBookMapper.selectDisCoupon(openid, time);
        //封装返回实体类
        coupons.sort(Comparator.comparing(Coupon::getValue).reversed());
        outOrderVO.setCoupons(coupons);
        outOrderVO.setDisCoupons(disableCoupons);
        Users users = userMapper.selectByOpenId(openid);
        outOrderVO.setUserType(users.getType());
        return outOrderVO;
    }



}
